import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_image_detail_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/vg_widgets/staggered/widgets/staggered_grid_view.dart';
import 'package:e_reception_flutter/vg_widgets/staggered/widgets/staggered_tile.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'event/refresh_smart_home_index_event.dart';
import 'event/refresh_style_image_event.dart';

/// 品牌或门店详情下方瀑布流页面
class SmartHomeStoreDetailListWidget extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeStoreDetailListWidget";
  //空间分类id
  final String stid;
  final String category;
  //style
  final String style;
  final String shid;

  const SmartHomeStoreDetailListWidget({Key key, this.stid, this.style, this.shid, this.category,}) : super(key:key);

  @override
  _SmartHomeStoreDetailListWidgetState createState() => _SmartHomeStoreDetailListWidgetState();

}


class _SmartHomeStoreDetailListWidgetState extends BasePagerState<SmartHomeStoreDetailListItemBean, SmartHomeStoreDetailListWidget>
    with AutomaticKeepAliveClientMixin, VgPlaceHolderStatusMixin {

  SmartHomeStoreDetailViewModel _viewModel;
  StreamSubscription _updateStreamSubscription;
  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeStoreDetailViewModel(this, stid: widget?.stid,
        style: widget?.style, shid: widget?.shid);
    _viewModel.refresh();
    _updateStreamSubscription =
        VgEventBus.global.streamController.stream.listen((event) {
          if(event is RefreshSmartHomeIndexEvent){
            _viewModel.refresh();
            return;
          }
          if(event is RefreshStyleImageEvent){
            _viewModel.setStyle(event?.style);
            _viewModel.refresh();
            return;
          }
        });
  }

  @override
  void dispose() {
    _updateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _toPlaceHolderWidget();
  }

  Widget _toPlaceHolderWidget(){
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        emptyWidget: _defaultEmptyCustomWidget(("综合" == (widget?.category??""))?"可展示品牌活动等海报内容～":"暂无内容"),
        errorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this,
            refreshBgColor: Colors.white,
            viewModel: _viewModel,
            child: _toStaggeredWidget())
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_smart_home_empty.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  ///瀑布流
  Widget _toStaggeredWidget(){
    return StaggeredGridView.countBuilder(
      padding: const EdgeInsets.symmetric(horizontal: 5.0),
      crossAxisCount: 4,
      itemCount: data?.length,
      shrinkWrap: true,
      staggeredTileBuilder: (int index){
        return new StaggeredTile.fit(2);
      },
      mainAxisSpacing: 5.0,
      crossAxisSpacing: 5.0,
      itemBuilder: (context, index){
        return _toItemWidget(index);
      },
    );

  }

  ///图片item
  Widget _toItemWidget(int index){
    SmartHomeStoreDetailListItemBean itemBean = data[index];
    String url = itemBean?.getCoverUrl();
    String picid = itemBean?.picid;
    bool isVideo = itemBean?.isVideo();
    String videoId = itemBean?.videoid;
    double imgWidth = (ScreenUtils.screenW(context) - 15)/2;
    double imgHeight = 0;
    int picWidth = int.parse(itemBean?.picsize?.split("*")[0]);
    int picHeight = int.parse(itemBean?.picsize?.split("*")[1]);
    double scale = picHeight/picWidth;
    if(scale == 1){
      imgHeight = imgWidth;
    }else{
      if(scale >= 4/3){
        imgHeight = (imgWidth*4)/3;
      }else{
        imgHeight = (imgWidth *3)/4;
      }
    }

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        SmartHomeImageDetailPage.navigatorPush(context, picid, videoId, widget?.shid, url, isVideo, itemBean?.isExample(), scale);
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.only(topLeft: Radius.circular(4), topRight: Radius.circular(4)),
            child: Stack(
              children: [
                Container(
                  width: imgWidth,
                  height: imgHeight,
                  child: VgCacheNetWorkImage(
                    url,
                    width: imgWidth,
                    height: imgHeight,
                    imageQualityType: ImageQualityType.middleUp,
                  ),
                ),
                Positioned(
                  left: imgWidth/2 - 20,
                  top: imgHeight/2 - 20,
                  child: Visibility(
                    visible: isVideo,
                    child: Image.asset(
                      "images/icon_smart_home_video_play.png",
                      width: 50,
                    ),
                  ),
                ),
                Visibility(
                  visible: itemBean?.isExample(),
                  child: Positioned(
                    top: 0,
                    left: 0,
                    child: Image.asset(
                      "images/icon_smart_home_example.png",
                      width: 42,
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  right: 0,
                  child: Visibility(
                    visible: (isVideo?? false),
                    child: Container(
                      width: 37,
                      height: 16,
                      decoration: BoxDecoration(
                          color: Color(0XFF000000).withOpacity(0.7),
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(4),
                              topRight: Radius.circular(4))),
                      child: Center(
                        child: Text(
                          VgDateTimeUtils.getSecondsToMinuteStr(data[index].videotime) ?? "00:00",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 9,
                              height: 1.2
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: 30,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(4), bottomRight: Radius.circular(4))
            ),
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    itemBean?.backup??"",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 10,
                      color: Color(0xFF8B93A5),
                    ),
                  ),
                ),
                SizedBox(width: 6,),
                Text(
                  itemBean?.getPicStorageStr(),
                  style: TextStyle(
                    fontSize: 10,
                    color: Color(0XFF8B93A5),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String getLabel(String style){
    String label = "";
    if(StringUtils.isNotEmpty(widget?.category) && "其他" != widget?.category){
      label += widget?.category;
      label += "/";
    }
    if(StringUtils.isNotEmpty(style)){
      label += ConstantRepository.of().getStyleNameByStyle(style);
    }
    if(label.endsWith("/")){
      label = label.substring(0, label.length-1);
    }
    return label;
  }

  @override
  bool get wantKeepAlive => true;
}
